﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using AprenderComendo.Infrastructure;
using Microsoft.Practices.Unity;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Conventions.Helpers;
using NHibernate.Context;
using NHibernate;
using AprenderComendo.Infrastructure.Persistence;

namespace AprenderComendo
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        
        private static IUnityContainer unityContainer;
        public static IUnityContainer UnityContainer
        {
            get
            {
                if (unityContainer == null)
                {
                    unityContainer = new UnityContainer();
                    unityContainer.RegisterInstance(unityContainer, new ContainerControlledLifetimeManager());
                }
                return unityContainer;
            }
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            EndRequest += Application_EndRequest;
            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(UnityContainer));
            ConfigureFluentSQLite();
            UnityContainer.RegisterType<IPersonRepository,ThoughtWorkerRepository>();
            UnityContainer.RegisterType<IPresentationRepository, PresentationRepository>();
            RegisterRoutes(RouteTable.Routes);
            
        }

        protected void Application_EndRequest(object sender, EventArgs eventArgs)
        {
            ISession session = (ISession)HttpContext.Current.Items[HttpContextLifetimeManager.Key];
            
            if (session != null)
            {
                if (session.Transaction != null &&
                    session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
                else
                    session.Flush();
                session.Close();
            }
        }

        private void ConfigureFluentSQLite()
        {
            var sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.UsingFile(@"C:\Users\3cents\Documents\Projects\DotNet\AprenderComendo\AprenderComendo\aprendercomendo.db"))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UnityControllerFactory>().Conventions.Add(DefaultLazy.Never()))
                .ExposeConfiguration(cfg =>
                                         {
                                             new SchemaExport(cfg).Execute(false, true,false);
                                         })
                .BuildSessionFactory();
            UnityContainer.RegisterInstance(sessionFactory, new ContainerControlledLifetimeManager());
            UnityContainer.RegisterType<ISession>(new HttpContextLifetimeManager(), new InjectionFactory(x => x.Resolve<ISessionFactory>().OpenSession()));
        }


    }
}